package com.example.socketfileupload;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhanghui
 * @date 2021/12/6 10:20
 */
public class Server {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        // 绑定端口启动服务
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器已启动");
        while (true) {
            Socket socket = serverSocket.accept();
            new ServerReaderThread(socket).start();
        }
    }
}

class ServerReaderThread extends Thread {
    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            // 读取文件类型
            String suffix = dataInputStream.readUTF();
            if (suffix.startsWith(".")) {
                suffix = suffix.substring(1);
            }
            System.out.println("服务端接受文件类型: " + suffix);
            FileOutputStream fileOutputStream = new FileOutputStream("serverSaveFile" + "." + suffix);
            byte[] buffer = new byte[1024];
            int readLength = 0;
            while ((readLength = dataInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, readLength);
            }
            fileOutputStream.close();
            System.out.println("服务端文件报保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
